<?php

namespace app\controller;

use app\BaseController;
use app\model\Role;
use app\model\User;
use think\Request;
use app\validator\RoleSave;

//  角色接口
class RoleController extends BaseController{
    public function list(Request $request){
        $limit = $request->param('limit') ?? 5;
        $page = $request->param('page') ?? 1;
        $name = $request->param('name') ?? '';
        $field = 'id,name,description,status';
        $role = new Role();
        $data = $role->_list($page, $limit, $name, $field);
        return json($data,$data['code']);
    }

    public function save(Request $request){
        $data = $request->param();

        $validate = new RoleSave();
        if (isset($data['id']) && intval($data['id']) >= 0)
            $scene = 'update'; // 更新数据
        else
            $scene = 'create';  // 添加数据

        //  验证参数
        if (!$validate->scene($scene)->check($data)) {
            return json([
                'code' => 400,
                'msg' => $validate->getError()
            ], 400);
        }

        $id =  $data['id'] ?? 0;
        $name = $data['name'];
        $description = $data['description'];
        $status = $data['status'];

        if ($id > 0) {
            // 更新数据
            $role = new Role();
            $fields = ['id','name','status','description'];
            $values = [$id,$name,$status,$description];
            $data = $role->_update($fields, $values);
            return json($data,$data['code']);
        } else {
            // 新增数据
            $role = new Role();
            $fields = ['name','status','description'];
            $values = [$name,$status,$description];
            $data = $role->_create($fields, $values);
            return json($data,$data['code']);
        }
    }

    public function delete(Request $request){
        $id = $request->param('id');
        $role = new Role();
        $data = $role->_delete($id);
        return json($data,$data['code']);
    }

    public function all_delete(Request $request){
        $ids = $request->param('idArray');
        $role = new Role();
        $data = $role->_allDelete($ids);
        return json($data,$data['code']);
    }

}